﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace AuthoringClientWordAddIn
{
    public partial class PublishingPaneControl : UserControl
    {
        private readonly ThisAddIn _thisAddIn;
        private readonly Dictionary<string, string> _documentProperties;

        public PublishingPaneControl(ThisAddIn thisAddIn, Dictionary<string, string> documentProperties)
        {
            InitializeComponent();
            _thisAddIn = thisAddIn;
            _documentProperties = documentProperties;
        }

        protected override void OnLoad(EventArgs e)
        {
            LoadProperties();
        }

        private void LoadProperties()
        {
            foreach (var documentProperty in _documentProperties)
            {
                AddPropertyRow(documentProperty.Key, documentProperty.Value);
            }
            fieldLayoutPanel.SetRow(publishButton, fieldLayoutPanel.RowCount - 1);
            fieldLayoutPanel.SetColumn(publishButton, 0);
        }

        private void AddPropertyRow(string propertyName, string defaultValue)
        {
            if (string.IsNullOrWhiteSpace(propertyName)) throw new ArgumentException("propertyName must have a value");

            var index = fieldLayoutPanel.RowCount - 1;

            InsertNewRow(fieldLayoutPanel, index);
            var label = new Label { Text = propertyName, Margin = new Padding(3, 6, 0, 0), AutoSize = true };
            fieldLayoutPanel.Controls.Add(label, 0, index);

            InsertNewRow(fieldLayoutPanel, index + 1);
            var textbox = new TextBox
            {
                Name = propertyName + "TextBox",
                Text = defaultValue,
                Dock = DockStyle.Fill,
                Margin = new Padding(3, 0, 3, 3),
                Tag = propertyName
            };
            fieldLayoutPanel.Controls.Add(textbox, 0, index + 1);
        }

        private static void InsertNewRow(TableLayoutPanel tableLayoutPanel, int index)
        {
            var rowStyle = new RowStyle(SizeType.AutoSize);
            tableLayoutPanel.RowCount++;
            tableLayoutPanel.RowStyles.Insert(index, rowStyle);
        }

        private void OnPublishButtonClick(object sender, EventArgs e)
        {
            SaveProperties();
            _thisAddIn.SaveDocumentProperties(_documentProperties);
            _thisAddIn.Publish();
        }

        private void SaveProperties()
        {
            foreach (var textBox in fieldLayoutPanel.Controls.OfType<TextBox>())
            {
                _documentProperties[(string)textBox.Tag] = textBox.Text;
            }
        }

    }
}
